package alfred.mdp.tsp.storage;

import alfred.mdp.messages.ProtocolMessage;
import alfred.mdp.tsp.Titanic;
import alfred.storage.MemoryMessagesStorage;
import org.zeromq.ZFrame;
import org.zeromq.ZMsg;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import static alfred.mdp.utils.Utils.asByteArray;

/**
 */
public class MemoryTspMessagesStorage extends MemoryMessagesStorage implements TspStorage<ZFrame, ZMsg> {
    private final BlockingQueue<ZFrame> pendingRequests = new LinkedBlockingQueue<ZFrame>();

    @Override
    public ZMsg findPendingRequest() {
        ZFrame key = pendingRequests.peek();
        if (key != null) {
            ZMsg pendingRequest = get(key);
            ZMsg result = new ZMsg();
            result.addLast(key);
            result.addAll(pendingRequest);
            return result;
        }
        return null;
    }

    @Override
    public void put(ZFrame key, ZMsg value) {
        super.put(key, value);
        if (Titanic.ResponseCode.PENDING.equals(ProtocolMessage.get(value, 0))) {
            pendingRequests.add(key);

        } else if (Titanic.ResponseCode.OK.equals(ProtocolMessage.get(value, 0))) {
            pendingRequests.remove(key);
        }
    }
}
